package com.lanyun.inteceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.lanyun.core.context.LoginContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

/**
 * 填充 createBy，createTime等公共字段的拦截器
 *
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/3/11
 */
@Component
@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class MybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        if (parameter == null) {
            return invocation.proceed();
        }
        // 获取当前登录用户的Id -- 待优化空指针
        String loginId = LoginContextHolder.getLoginId();
        if (StringUtils.isBlank(loginId)) {
            return invocation.proceed();
        }

        // 只处理增加和删除的sql语句
        if (SqlCommandType.INSERT == sqlCommandType || SqlCommandType.UPDATE == sqlCommandType) {
            replaceEntityProperty(parameter, loginId, sqlCommandType);
        }
        return invocation.proceed();
    }

    // 处理增加和删除的sql语句
    private void replaceEntityProperty(Object parameter, String loginId, SqlCommandType sqlCommandType) {
        if (parameter instanceof Map) {
            replaceMap((Map) parameter, loginId, sqlCommandType);
        } else {
            replace(parameter, loginId, sqlCommandType);
        }

    }

    private void replaceMap(Map parameter, String loginId, SqlCommandType sqlCommandType) {
        for (Object value : parameter.values()) {
            replace(value, loginId, sqlCommandType);
        }
    }

    private void replace(Object parameter, String loginId, SqlCommandType sqlCommandType) {
        // 处理 INSERT 语句
        if (SqlCommandType.INSERT == sqlCommandType) {
            dealInsert(parameter, loginId);
        } else {  // 处理 UPDATE 语句
            dealUpdate(parameter, loginId);
        }
    }

    // 处理 INSERT 语句
    private void dealInsert(Object parameter, String loginId) {
        Field[] fields = getAliiFields(parameter);
        for (Field field : fields) {
            try {
                // 设置为可访问
                field.setAccessible(true);
                // 获取到当前类里的属性相应的属性值
                Object o = field.get(parameter);
                /**
                 * 如果循环到当前的属性值不为空，那么不用做处理，直接跳过
                 */
                if (Objects.nonNull(o)) {
                    field.setAccessible(false);
                    continue;
                }

                /**
                 * 填充空属性
                 */
                if ("isDeleted".equals(field.getName())) {
                    // 默认未删除
                    field.set(parameter, "undeleted");
                    field.setAccessible(false);
                } else if ("createdBy".equals(field.getName())) {
                    field.set(parameter, loginId);
                    field.setAccessible(false);
                } else if ("createdTime".equals(field.getName())) {
                    field.set(parameter, new Date());
                    field.setAccessible(false);
                } else {
                    field.setAccessible(false);
                }


            } catch (Exception e) {
                log.error("dealInsert.error:{}", e.getMessage(), e);
            }
        }
    }

    // 处理 UPDATE 语句
    private void dealUpdate(Object parameter, String loginId) {
        Field[] fields = getAliiFields(parameter);
        for (Field field : fields) {
            try {
                // 设置为可访问
                field.setAccessible(true);
                // 获取到当前类里的属性相应的属性值
                Object o = field.get(parameter);
                /**
                 * 如果循环到当前的属性值不为空，那么不用做处理，直接跳过
                 */
                if (Objects.nonNull(o)) {
                    field.setAccessible(false);
                    continue;
                }

                /**
                 * 填充空属性
                 */
                if ("updateBy".equals(field.getName())) {
                    field.set(parameter, loginId);
                    field.setAccessible(false);
                } else if ("updateTime".equals(field.getName())) {
                    field.set(parameter, new Date());
                    field.setAccessible(false);
                } else {
                    field.setAccessible(false);
                }


            } catch (Exception e) {
                log.error("dealUpdate.error:{}", e.getMessage(), e);
            }
        }
    }

    // 获取该对象所有属性字段
    private Field[] getAliiFields(Object object) {
        Class<?> clazz = object.getClass();
        // 存放的是 clazz 对象的所有字段名
        List<Field> fieldList = new LinkedList<>();
        while (clazz != null) {
            /**
             * clazz.getDeclaredFields() 拿到所有字段名
             */
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            // 父级对象
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }
}
